package com.service.impl;

import com.dao.StudentMapper;
import com.model.Student;
import com.service.StudentService;
import com.utils.PageParam;
import com.utils.Pager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service("studentService")
public class StudentServiceImpl implements StudentService {


    @Resource
    private StudentMapper studentMapper;

    @Override
    public Pager<Student> getStudentPage(String clazzCode, String studentName, PageParam pageParam) {
        Pager<Student> pager = new Pager<>(0, new ArrayList<>());
        String search = "";
        if (StringUtils.isNotEmpty(studentName)) {
            search = "%" + studentName + "%";
        }
        List<String> clazzCodes = null;
        if (StringUtils.isNotEmpty(clazzCode)) {
            clazzCodes = Arrays.asList(clazzCode.split(","));
        }
        int totalCount = studentMapper.findStudentCount(clazzCodes, search);
        if (totalCount > 0) {
            List<Student> list = studentMapper.findStudents(clazzCodes, search, pageParam);
            pager.setTotalCount(totalCount);
            pager.setList(list);
        }
        return pager;
    }

    @Override
    public void updateStudent(Student student) {
        studentMapper.updateStudent(student);
    }

    @Override
    public void saveStudent(Student student) {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyHHmmss");
        String timeStr = sdf.format(now);
        String studentId = "stu" + timeStr;
        student.setStudentId(studentId);
        studentMapper.insertStudent(student);
    }

    @Override
    public void delStudent(List<Long> ids) {
        studentMapper.delStudent(ids);
    }

    @Override
    public List<Student> getClazzStudents(String clazzCode) {
        return studentMapper.findClazzStudents(clazzCode);
    }

    @Override
    public void updateStudentInfo(Long id, String studentName, String password) {
        if (StringUtils.isNotEmpty(password)) {
            studentMapper.updatePassword(id, studentName, password);
        } else {
            studentMapper.updateName(id, studentName);
        }
    }

    @Override
    public Student getStudentByName(String username) {
        return studentMapper.findStudentByName(username);
    }
}
